package com.sky.aspect;

import com.sky.annotation.AutoFill;
import com.sky.constant.AutoFillConstant;
import com.sky.context.BaseContext;
import com.sky.enumeration.OperationType;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.stereotype.Component;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.time.LocalDateTime;

@Aspect //标识当前的类是一个切面类
@Component
public class AutoFillAspect {

    @Pointcut("execution(* com.sky.mapper.*.*.*(..)) && @annotation(com.sky.annotation.AutoFill)")
    public void pointcut(){}
    
    @Before("pointcut()")
    public void autoFill(JoinPoint joinPoint) throws NoSuchMethodException, InvocationTargetException, IllegalAccessException {
        //1. 通过joinPoint对象拿到方法的签名数据
        MethodSignature signature = (MethodSignature) joinPoint.getSignature();

        //2. 通过方法的签名获取方法上的注解
        AutoFill autoFill = signature.getMethod().getAnnotation(AutoFill.class);

        //3. 通过方法的签名获取方法的参数
        Object args = joinPoint.getArgs()[0];

        //4. 根据注解的值来判断当前增强的是insert还是update
        if(OperationType.INSERT.equals(autoFill.value())){
            //新增
            //5. 根据反射获取setUpdateUser/setUpdateTime方法 然后通过反射给参数对象赋值
            Method setCreateTime = args.getClass().getDeclaredMethod(AutoFillConstant.SET_CREATE_TIME, LocalDateTime.class);
            Method setUpdateTime = args.getClass().getDeclaredMethod(AutoFillConstant.SET_UPDATE_TIME, LocalDateTime.class);
            Method setCreateUser = args.getClass().getDeclaredMethod(AutoFillConstant.SET_CREATE_USER, Long.class);
            Method setUpdateUser = args.getClass().getDeclaredMethod(AutoFillConstant.SET_UPDATE_USER, Long.class);

            setCreateTime.invoke(args, LocalDateTime.now());
            setUpdateTime.invoke(args, LocalDateTime.now());
            setCreateUser.invoke(args, BaseContext.getCurrentId());
            setUpdateUser.invoke(args, BaseContext.getCurrentId());

        }else if(OperationType.UPDATE.equals(autoFill.value())){
            //修改
            Method setUpdateTime = args.getClass().getDeclaredMethod(AutoFillConstant.SET_UPDATE_TIME, LocalDateTime.class);
            Method setUpdateUser = args.getClass().getDeclaredMethod(AutoFillConstant.SET_UPDATE_USER, Long.class);

            setUpdateTime.invoke(args, LocalDateTime.now());
            setUpdateUser.invoke(args, BaseContext.getCurrentId());
        }
    }
}
